//
// Created by Administrator on 2020/10/27.
//

#include "../include/l1IntfApi.h"
#include "l1IntfUl/l1IntfUl.h"
#include "l1IntfDl/l1IntfDl.h"
#include "l1ApiAdpt/l1ApiAdpt.h"

S_RanL2L1IntfContext *gpRanL2L1IntfContext = NULL;

int32_t RAN_L2_L1I_Init(void)
{
    int32_t rc;

    gpRanL2L1IntfContext = OS_MemCalloc(1, sizeof(S_RanL2L1IntfContext));
    IF_RETURN(==, NULL, gpRanL2L1IntfContext, O5G_RC_ER, "RAN_L2_L1I_Init() OS_MemCalloc() error!\n");

    rc = OS_SelectInit(&gpRanL2L1IntfContext->ulSelector, NULL);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Init() OS_SelectInit() error!\n");

    rc = OS_SelectInit(&gpRanL2L1IntfContext->dlSelector, NULL);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Init() OS_SelectInit() error!\n");

    gpRanL2L1IntfContext->ulPoller = POLLER_Create(POLL_FD_NUM_MAX);
    IF_RETURN(==, NULL, gpRanL2L1IntfContext->ulPoller, O5G_RC_ER, "RAN_L2_L1I_Init() POLLER_Create(ulPoller) error!\n");

    gpRanL2L1IntfContext->dlPoller = POLLER_Create(POLL_FD_NUM_MAX);
    IF_RETURN(==, NULL, gpRanL2L1IntfContext->dlPoller, O5G_RC_ER, "RAN_L2_L1I_Init() POLLER_Create(dlPoller) error!\n");

    rc = RAN_L2_L1_ADPT_Init();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Init() RAN_L2_L1_ADPT_Init() error!\n");

    return O5G_RC_OK;
}

int32_t RAN_L2_L1I_Final(void)
{
    int32_t rc;

    rc = OS_SelectFinal(&gpRanL2L1IntfContext->ulSelector);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Final() OS_SelectFinal() error!\n");

    rc = OS_SelectFinal(&gpRanL2L1IntfContext->dlSelector);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Final() OS_SelectFinal() error!\n");

    POLLER_Destroy(gpRanL2L1IntfContext->ulPoller);
    POLLER_Destroy(gpRanL2L1IntfContext->dlPoller);

    rc = RAN_L2_L1_ADPT_Final();
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Final() RAN_L2_L1_ADPT_Final() error!\n");

    OS_MemFree(gpRanL2L1IntfContext);

    return O5G_RC_OK;
}

int32_t RAN_L2_L1I_Start(void)
{
    int32_t rc;

    rc = OS_ThreadCreate(&gpRanL2L1IntfContext->ulTid, RAN_L2_L1I_UL_Task, NULL);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Start() OS_ThreadCreate() error!\n");

    rc = OS_ThreadCreate(&gpRanL2L1IntfContext->dlTid, RAN_L2_L1I_DL_Task, NULL);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Start() OS_ThreadCreate() error!\n");

    return O5G_RC_OK;
}

int32_t RAN_L2_L1I_Stop(void)
{
    int32_t rc;

    rc = OS_ThreadCancel(gpRanL2L1IntfContext->ulTid);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Stop() OS_ThreadCancel() error!\n");

    rc = OS_ThreadCancel(gpRanL2L1IntfContext->dlTid);
    IF_RETURN(!=, O5G_RC_OK, rc, O5G_RC_ER, "RAN_L2_L1I_Stop() OS_ThreadCancel() error!\n");

    return O5G_RC_OK;
}
